import { Card, Tag, Badge, Empty, Select, Space, Popover, Modal, Descriptions } from 'antd';
import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { getMyCourses, getTeacherByName } from '../../api/student';
import dayjs from 'dayjs';
import { UserOutlined, MailOutlined, PhoneOutlined, BookOutlined, TeamOutlined, TrophyOutlined } from '@ant-design/icons';

export default function Home() {
  const { data: list = [], isLoading } = useQuery({ queryKey: ['me', 'courses'], queryFn: getMyCourses });

  const today = dayjs().day() || 7;
  const weekdayLabels = ['周一','周二','周三','周四','周五','周六','周日'];
  const weeks = Array.from({ length: 20 }, (_, i) => i + 1);

  // 将时间映射为节次索引
  function timeToPeriod(start: string): number {
    const [h, m] = start.split(':').map(Number);
    const minutes = h * 60 + m;
    if (minutes < 9 * 60) return 0; // 8:00 -> 1-2节
    if (minutes < 12 * 60) return 1; // 10:00 -> 3-4节
    if (minutes < 15 * 60) return 2; // 14:00 -> 5-6节
    if (minutes < 18 * 60) return 3; // 16:00 -> 7-8节
    return 4; // 19:00 -> 9-10节
  }

  // 注意：cellMap 移到 TimetableCard 内根据选中周动态计算

  return (
    <div className="space-y-4">
      <TimetableCard list={list} weekdayLabels={weekdayLabels} weeks={weeks} timeToPeriod={timeToPeriod} />
    </div>
  );
}

function TimetableCard({ list, weekdayLabels, weeks, timeToPeriod }: { list: any[]; weekdayLabels: string[]; weeks: number[]; timeToPeriod: (s:string)=>number }) {
  const periods = ['1-2节', '3-4节', '5-6节', '7-8节', '9-10节'];
  // 定义每个时间段的默认时间范围
  const defaultTimeRanges = ['08:00-10:00', '10:00-12:00', '14:00-16:00', '16:00-18:00', '19:00-21:00'];
  const [selectedWeek, setSelectedWeek] = useState<number>(1);
  const [teacherModalVisible, setTeacherModalVisible] = useState(false);
  const [selectedTeacherName, setSelectedTeacherName] = useState<string>('');
  const [openPopoverId, setOpenPopoverId] = useState<string | null>(null);
  const [isClickingTeacher, setIsClickingTeacher] = useState(false);

  const { data: teacherInfo, isLoading: teacherLoading } = useQuery({
    queryKey: ['teacher', selectedTeacherName],
    queryFn: () => getTeacherByName(selectedTeacherName),
    enabled: teacherModalVisible && !!selectedTeacherName,
  });

  const handleTeacherClick = (teacherName: string, courseId: string, e: React.MouseEvent) => {
    e.stopPropagation(); // 阻止事件冒泡到Popover
    e.preventDefault(); // 阻止默认行为
    setIsClickingTeacher(true);
    // 先关闭Popover
    setOpenPopoverId(null);
    // 立即设置教师名称并打开Modal
    setSelectedTeacherName(teacherName);
    // 使用setTimeout确保Popover关闭后再打开Modal
    setTimeout(() => {
      setTeacherModalVisible(true);
      setIsClickingTeacher(false);
    }, 150);
  };

  // 依据周次构建 cellMap（只放置包含该周的课）
  // 同时存储时间段信息以便在左侧显示时间
  const cellMap: Record<string, { course: any; active: boolean; timeSlot: any }[]> = useMemo(() => {
    const map: Record<string, { course: any; active: boolean; timeSlot: any }[]> = {};
    for (const c of list) {
      for (const s of c.timeSlots) {
        const inByArray = s.weeks ? s.weeks.includes(selectedWeek) : true;
        const inByRange = s.startWeek && s.endWeek ? (selectedWeek >= s.startWeek && selectedWeek <= s.endWeek) : true;
        const active = inByArray && inByRange;
        const p = timeToPeriod(s.start);
        const key = `${s.dayOfWeek}-${p}`;
        if (!map[key]) map[key] = [];
        map[key].push({ course: c, active, timeSlot: s });
      }
    }
    return map;
  }, [list, selectedWeek, timeToPeriod]);

  return (
    <Card
      loading={!list}
      title={
        <Space>
          <span>课表</span>
          <span className="text-slate-400 text-sm">（第</span>
          <Select value={selectedWeek} onChange={(v)=>setSelectedWeek(v)} options={weeks.map(w=>({value:w,label:String(w)}))} style={{ width: 96 }} />
          <span className="text-slate-400 text-sm">周）</span>
        </Space>
      }
    >
      {/* 表头 */}
      <div className="grid" style={{ gridTemplateColumns: '120px repeat(7, 1fr)' }}>
        <div className="text-slate-500 text-sm py-2 px-3">时间</div>
        {weekdayLabels.map((d, i) => (
          <div key={i} className="text-slate-500 text-sm py-2 px-3 text-center">{d}</div>
        ))}
      </div>
      {/* 网格 */}
      <div className="border rounded-md overflow-hidden">
        {periods.map((label, rowIdx) => {
          // 获取该行所有课程的时间（用于左侧显示）
          const timeRanges = new Set<string>();
          for (let day = 1; day <= 7; day++) {
            const key = `${day}-${rowIdx}`;
            const entries = cellMap[key] || [];
            entries.forEach(({ timeSlot }) => {
              timeRanges.add(`${timeSlot.start}-${timeSlot.end}`);
            });
          }
          const uniqueTimeRanges = Array.from(timeRanges);
          // 如果有课程时间则显示课程时间，否则显示默认时间
          const displayTime = uniqueTimeRanges.length > 0 ? uniqueTimeRanges.join(' / ') : defaultTimeRanges[rowIdx];
          
          return (
            <div key={rowIdx} className="grid border-b last:border-b-0" style={{ gridTemplateColumns: '120px repeat(7, 1fr)' }}>
              <div className="py-6 px-3 text-slate-600 border-r bg-slate-50">
                <div>{label}</div>
                <div className="text-xs mt-1 text-slate-500">
                  {displayTime}
                </div>
              </div>
              {Array.from({ length: 7 }, (_, colIdx) => {
                const day = colIdx + 1;
                const key = `${day}-${rowIdx}`;
                const entries = cellMap[key] || [];
                
                // 按课程ID去重，每个课程只显示一个卡片
                const uniqueCourses = new Map<string, { course: any; active: boolean; timeSlots: any[] }>();
                entries.forEach(({ course, active, timeSlot }) => {
                  if (!uniqueCourses.has(course.id)) {
                    uniqueCourses.set(course.id, { course, active, timeSlots: [] });
                  }
                  const entry = uniqueCourses.get(course.id)!;
                  entry.timeSlots.push(timeSlot);
                  // 如果任何一个时间段是active的，整个课程就是active的
                  if (active) {
                    entry.active = true;
                  }
                });
                
                return (
                  <div key={colIdx} className="relative h-24 border-r last:border-r-0">
                    {Array.from(uniqueCourses.values()).map(({ course, active, timeSlots }) => {
                      // 获取所有教室（去重）
                      const rooms = [...new Set(timeSlots.map(ts => ts.room).filter(Boolean))];
                      // 获取时间范围
                      const timeRanges = timeSlots.map(ts => `${ts.start}-${ts.end}`).join(' / ');
                      
                      const courseDetailContent = (
                        <div className="w-64">
                          <div className="font-semibold text-base mb-3">{course.name}</div>
                          <div className="space-y-2 text-sm">
                            <div className="flex items-center">
                              <span className="text-slate-500 w-16">时间：</span>
                              <span>{timeRanges}</span>
                            </div>
                            <div className="flex items-center">
                              <span className="text-slate-500 w-16">教师：</span>
                              <span 
                                className="text-blue-600 hover:text-blue-800 cursor-pointer hover:underline"
                                onClick={(e) => {
                                  handleTeacherClick(course.teacherName, course.id, e);
                                }}
                                onMouseDown={(e) => {
                                  // 阻止mousedown事件冒泡，防止触发Popover的关闭
                                  e.stopPropagation();
                                }}
                                onMouseUp={(e) => {
                                  // 阻止mouseup事件冒泡
                                  e.stopPropagation();
                                }}
                              >
                                {course.teacherName}
                              </span>
                            </div>
                            {rooms.length > 0 && (
                              <div className="flex items-center">
                                <span className="text-slate-500 w-16">教室：</span>
                                <span>{rooms.join(' / ')}</span>
                              </div>
                            )}
                            <div className="flex items-center">
                              <span className="text-slate-500 w-16">学分：</span>
                              <span>{course.credit}</span>
                            </div>
                            <div className="flex items-center">
                              <span className="text-slate-500 w-16">周次：</span>
                              <span>{formatWeekRange(course)}</span>
                            </div>
                            <div className="flex items-center">
                              <span className="text-slate-500 w-16">选课人数：</span>
                              <span>{course.enrolledCount}/{course.capacity}</span>
                            </div>
                          </div>
                        </div>
                      );
                      
                      return (
                        <Popover 
                          key={course.id}
                          content={courseDetailContent}
                          title={null}
                          trigger={[]}
                          placement="right"
                          open={openPopoverId === course.id && !isClickingTeacher}
                          onOpenChange={(open) => {
                            // 如果正在点击教师，不关闭Popover
                            if (isClickingTeacher) {
                              return;
                            }
                            if (!open) {
                              setOpenPopoverId(null);
                            } else {
                              // 关闭其他已打开的Popover
                              setOpenPopoverId(course.id);
                            }
                          }}
                          destroyTooltipOnHide
                          overlayStyle={{ zIndex: 1000 }}
                          getPopupContainer={(triggerNode) => triggerNode.parentElement || document.body}
                        >
                          <div
                            className={`absolute left-2 right-2 top-2 bottom-2 rounded-md border p-2 text-xs cursor-pointer transition-all hover:shadow-md ${active ? 'bg-blue-50 border-blue-300' : 'bg-slate-50 border-slate-200 opacity-50'}`}
                            onClick={(e) => {
                              e.stopPropagation();
                              // 如果当前Popover已打开，则关闭；否则打开
                              if (openPopoverId === course.id) {
                                setOpenPopoverId(null);
                              } else {
                                setOpenPopoverId(course.id);
                              }
                            }}
                          >
                            <div className="font-medium truncate">{course.name}</div>
                            <div className="mt-1 space-x-2">
                              <Tag color="blue">{formatWeekRange(course)}</Tag>
                              {rooms.length > 0 && (
                                <Tag color="green">{rooms[0]}{rooms.length > 1 ? `等${rooms.length}个` : ''}</Tag>
                              )}
                            </div>
                          </div>
                        </Popover>
                      );
                    })}
                  </div>
                );
              })}
            </div>
          );
        })}
      </div>
      {list.length === 0 && <Empty className="mt-4" description="暂无课程" />}
      
      {/* 教师信息Modal */}
      <Modal
        title={
          <div className="flex items-center">
            <UserOutlined className="mr-2 text-blue-500" />
            <span>教师信息</span>
          </div>
        }
        open={teacherModalVisible}
        onCancel={() => {
          setTeacherModalVisible(false);
          setSelectedTeacherName('');
        }}
        footer={null}
        width={600}
        zIndex={2000}
        maskClosable={false}
      >
        {teacherLoading ? (
          <div className="text-center py-8 text-gray-400">加载中...</div>
        ) : teacherInfo ? (
          <Descriptions column={1} bordered>
            <Descriptions.Item label={<span><UserOutlined className="mr-1" />姓名</span>}>
              {teacherInfo.name}
            </Descriptions.Item>
            <Descriptions.Item label={<span><TeamOutlined className="mr-1" />所属学院</span>}>
              {teacherInfo.college || '-'}
            </Descriptions.Item>
            <Descriptions.Item label={<span><TrophyOutlined className="mr-1" />职称</span>}>
              {teacherInfo.title || '-'}
            </Descriptions.Item>
            {teacherInfo.email && (
              <Descriptions.Item label={<span><MailOutlined className="mr-1" />邮箱</span>}>
                {teacherInfo.email}
              </Descriptions.Item>
            )}
            {teacherInfo.phone && (
              <Descriptions.Item label={<span><PhoneOutlined className="mr-1" />电话</span>}>
                {teacherInfo.phone}
              </Descriptions.Item>
            )}
            {teacherInfo.researchArea && (
              <Descriptions.Item label={<span><BookOutlined className="mr-1" />研究方向</span>}>
                {teacherInfo.researchArea}
              </Descriptions.Item>
            )}
            {teacherInfo.publishedPapers !== undefined && (
              <Descriptions.Item label="发表论文数">
                {teacherInfo.publishedPapers} 篇
              </Descriptions.Item>
            )}
            {teacherInfo.intro && (
              <Descriptions.Item label="个人简介">
                {teacherInfo.intro}
              </Descriptions.Item>
            )}
          </Descriptions>
        ) : (
          <div className="text-center py-8 text-gray-400">未找到教师信息</div>
        )}
      </Modal>
    </Card>
  );
}

function formatWeekRange(course: any): string {
  let minStart: number | undefined;
  let maxEnd: number | undefined;
  for (const s of course.timeSlots || []) {
    if (s.weeks && s.weeks.length) {
      const wmin = Math.min(...s.weeks);
      const wmax = Math.max(...s.weeks);
      minStart = minStart === undefined ? wmin : Math.min(minStart, wmin);
      maxEnd = maxEnd === undefined ? wmax : Math.max(maxEnd, wmax);
    }
    if (s.startWeek !== undefined) {
      minStart = minStart === undefined ? s.startWeek : Math.min(minStart, s.startWeek);
    }
    if (s.endWeek !== undefined) {
      maxEnd = maxEnd === undefined ? s.endWeek : Math.max(maxEnd, s.endWeek);
    }
  }
  if (minStart !== undefined && maxEnd !== undefined) return `第${minStart}-${maxEnd}周`;
  return '周次待定';
}


